package com.campus.controller;

import com.campus.domain.dto.AnnouncementQueryDTO;
import com.campus.domain.dto.PublishAnnouncementDTO;
import com.campus.domain.dto.UserDTO;
import com.campus.domain.vo.AnnouncementVO;
import com.campus.domain.vo.PageResultVO;
import com.campus.domain.vo.Result;
import com.campus.service.IAnnouncementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/announcement")
public class AnnouncementController {

    @Autowired
    private IAnnouncementService announcementService;

    /**
     * 发布公告
     */
    @PostMapping("/publish")
    @PreAuthorize("@ex.hasAuthority('announcement:publish')")
    public Result<String> publishAnnouncement(@RequestBody PublishAnnouncementDTO dto) {
        // 获取当前登录用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDTO userDTO = (UserDTO) authentication.getPrincipal();
        Long userId = userDTO.getId();

        // 调用service发布公告
        announcementService.publishAnnouncement(dto, userId);

        return Result.ok("发布成功");
    }

    /**
     * 获取公告列表（分页）
     */
    @GetMapping("/list")
    public Result<PageResultVO<AnnouncementVO>> getAnnouncementList(AnnouncementQueryDTO queryDTO) {
        PageResultVO<AnnouncementVO> result = announcementService.getAnnouncementList(queryDTO);
        return Result.ok(result);
    }

    /**
     * 获取公告详情
     */
    @GetMapping("/detail/{id}")
    public Result<AnnouncementVO> getAnnouncementDetail(@PathVariable("id") Long id) {
        AnnouncementVO announcement = announcementService.getAnnouncementDetail(id);
        return Result.ok(announcement);
    }

    /**
     * 删除公告
     */
    @DeleteMapping("/delete/{id}")
    public Result<String> deleteAnnouncement(@PathVariable("id") Long id) {
        // 获取当前登录用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDTO userDTO = (UserDTO) authentication.getPrincipal();
        Long userId = userDTO.getId();

        // 调用service删除公告
        announcementService.deleteAnnouncement(id, userId);

        return Result.ok("删除成功");
    }
}

